package sortingRMI_client;

import java.util.Observable;
import java.util.Observer;

@SuppressWarnings("unchecked")
public class ListJoiner implements Observer {
	public int lastThreadNumber;
	public  int currentThreadNumber;
	public int threadsProcessed;
	public int highThread;
	public int threadsRecieved;
	public int totalLengthOfArray;
	public int totalArrayToBeJoined;
	public ListJoiner lj;
	public Comparable[][] bucketStore = new Comparable[8][];
	public Comparable[] tempJoinedArray;
	public Comparable[] tempSortedArray;
	
	public ListJoiner() {
		super();
	}
	
	private void join(Comparable[] arrayToBeJoined) {	

		if (tempSortedArray == null) {
			// this is the first array to be joined in our tempJoinedArray!
			tempSortedArray = new Comparable[totalLengthOfArray];
			totalArrayToBeJoined += arrayToBeJoined.length;
			
			System.arraycopy(arrayToBeJoined,0,tempSortedArray,0,arrayToBeJoined.length);
			
			threadsProcessed++;
		} else {
			
			System.arraycopy(arrayToBeJoined,0,tempSortedArray,totalArrayToBeJoined,arrayToBeJoined.length);
			totalArrayToBeJoined += arrayToBeJoined.length;
			
		}
			lastThreadNumber = currentThreadNumber;
			threadsProcessed++;

	}
	    
	public void  printJoinedList() {
		int n;
		System.out.println("\nJoined Array Contents : \n");
		for (n=0; n<  tempSortedArray.length; n++) {
			System.out.println(((MuziekCD) tempSortedArray[n]).getArtist() + " : " + ((MuziekCD) tempSortedArray[n]).getTitle() + " : " + ((MuziekCD) tempSortedArray[n]).getYear() + " Thread : "+ ((MuziekCD) tempSortedArray[n]).getThreadName());
		}
	}

    public ListJoiner getListJoiner() {
    	ListJoiner lj = new ListJoiner();
    	return lj;
    }
	
	@Override
	public void update(Observable arg0, Object o) {
		int i;
		SorterThread temp = (SorterThread) arg0;
		threadsRecieved++;
		Comparable[] tempArray = ((SorterThread) temp).getSortedArray();
		
		if ( tempArray.length > 0) {
			totalLengthOfArray = totalLengthOfArray+tempArray.length;
		}
		
		bucketStore[Integer.parseInt(((MuziekCD)tempArray[0]).getThreadName())] = tempArray;
		
		if(Integer.parseInt(((MuziekCD)tempArray[0]).getThreadName()) > highThread) {
			highThread = Integer.parseInt(((MuziekCD)tempArray[0]).getThreadName());
		}
		
		if(threadsRecieved == bucketStore.length) {
			for( i =0; i < bucketStore.length; i++) {
				join(bucketStore[i]);
				}
			//printJoinedList();
			}
	}
}

